package com.qingmeng.applyjob.portal.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.qingmeng.applyjob.mapper.*;
import com.qingmeng.applyjob.model.*;
import com.qingmeng.applyjob.portal.bo.PortalUserDetails;
import com.qingmeng.applyjob.portal.enums.RegisterResult;
import com.qingmeng.applyjob.portal.model.dto.UserRegisterParam;
import com.qingmeng.applyjob.portal.model.vo.UserVo;
import com.qingmeng.applyjob.portal.service.UserService;
import com.qingmeng.applyjob.portal.utils.SecurityUtils;
import com.qingmeng.applyjob.security.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户操作业务处理
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private SkillMapper skillMapper;

    @Autowired
    private EducationMapper educationMapper;


    @Override
    public User getUserByUsername(String username) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(users)) {
            User user = users.get(0);
            return user;
        }
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) {
        User user = getUserByUsername(userName);
        if (user != null) {
            return new PortalUserDetails(user);
        }
        return null;
    }

    @Override
    public RegisterResult register(UserRegisterParam param) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(param.getUsername());
        if (userMapper.countByExample(userExample) > 0) {
            return RegisterResult.USERNAME_EXIST;
        }

        User user = new User();
        user.setUsername(param.getUsername());
        user.setPassword(passwordEncoder.encode(param.getPassword()));
        user.setGender(param.getGender());
        user.setAge(param.getAge());
        user.setPhone(param.getPhone());
        user.setEmail(param.getEmail());
        user.setIntroduce(param.getIntroduce());
        user.setAvatar(param.getAvatar());
        user.setCreateTime(new Date());

        if (userMapper.insertSelective(user) > 0) {
            return RegisterResult.SUCCESS;
        }

        return RegisterResult.FAILED;
    }

    @Override
    public Map<String, String> login(String username, String password) {
        // 使用 username 和 password 构造一个 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = null;
        try {
            // 验证用户名和密码
            authenticate = authenticationManager.authenticate(token);
        } catch (AuthenticationException e) {
            logger.error("用户名或密码错误：{}", e.toString());
            return null;
        }
        // 将authenticate添加到安全框架的上下文中
        SecurityContextHolder.getContext().setAuthentication(authenticate);

        // 定义返回给前端的Map
        Map<String, String> tokenMap = new HashMap<>();
        if (authenticate != null) {
            // 从验证结果返回的authenticate中获取UserDetails对象
            UserDetails userDetails = (UserDetails) authenticate.getPrincipal();
            // 根据UserDetails对象生成token字符串
            String tokenString = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", tokenString);
            tokenMap.put("tokenHead", jwtTokenUtil.getTokenHead());
            tokenMap.put("tokenHeader", jwtTokenUtil.getTokenHeader());
        }
        return tokenMap;
    }

    @Override
    public UserVo getPersonal() {
        UserVo userVo = new UserVo();
        User currentUser = SecurityUtils.getCurrentUser();
        userVo.setUserId(currentUser.getId());
        userVo.setUsername(currentUser.getUsername());
        userVo.setAvatar(currentUser.getAvatar());
        if (currentUser.getUpdateTime() == null){
            userVo.setUpdateTime(null);
        }else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            String format = simpleDateFormat.format(currentUser.getUpdateTime());
            userVo.setUpdateTime(format);
        }
        //计算简历完成度
        double rPerfection = 0.00;
        int temp = 0;
        ProjectExample projectExample = new ProjectExample();
        projectExample.createCriteria().andUserIdEqualTo(currentUser.getId());
        List<Project> projectList = projectMapper.selectByExample(projectExample);
        if (projectList != null && projectList.size() > 0) temp++;
//        logger.info("检测完project后为：{}",temp);
        WorkExample workExample = new WorkExample();
        workExample.createCriteria().andUserIdEqualTo(currentUser.getId());
        List<Work> workList = workMapper.selectByExample(workExample);
        if (workList != null && workList.size() > 0) temp++;
//        logger.info("检测完work后为：{}",temp);
        EducationExample educationExample = new EducationExample();
        educationExample.createCriteria().andUserIdEqualTo(currentUser.getId());
        List<Education> educationList = educationMapper.selectByExample(educationExample);
        if (educationList != null && educationList.size() > 0) temp++;
//        logger.info("检测完education后为：{}",temp);
        SkillExample skillExample = new SkillExample();
        skillExample.createCriteria().andUserIdEqualTo(currentUser.getId());
        List<Skill> skillList = skillMapper.selectByExample(skillExample);
        if (skillList != null && skillList.size() > 0) temp++;
//        logger.info("检测完skill后为：{}",temp);
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdEqualTo(currentUser.getId());
        List<User> users = userMapper.selectByExample(userExample);
        if (users != null && users.size() > 0){
            if (users.get(0).getIntroduce() != null){
                temp++;
//                logger.info("检测完user后为：{}",temp);
            }
        }
//        logger.info("{}",temp);
        rPerfection = temp / 5.0;
//        logger.info("{}",rPerfection);
        double resumePerfection = rPerfection * 100;
//        logger.info("{}",resumePerfection);
        userVo.setResumePerfection(resumePerfection);

        userVo.setCoachNum(0);
        userVo.setGoodRating(0.00);
        userVo.setInwardPushNum(0);
        return userVo;
    }
}
